﻿using System;
using System.Collections.Generic;

namespace TopHero
{
    public class HeroIdleState : Singleton<HeroIdleState>, State<Hero>
    {
        public void Enter(Hero hero)
        {
        }

        public void Execute(Hero hero)
        {
            Path path = hero.path;
            Vector2 position = hero.position;

            Vector2 currentWaryPoint = path.CurrentWayPoint();

            if ((currentWaryPoint - position).sqrMagnitude < GameDefine.WAY_POINT_SEEK_DIST_SQ)
            {
                path.NextWayPoint();

                MessageDispatcher.Instance.DispatchMsg(0, hero.ID(), hero.world.GetCell(position).ID(),
                    MessageType.HeroArriveCell);
                
                Cell cell = hero.world.GetCell(position);
                List<Monster> monsters = cell.GetMonsters();
                if (monsters.Count > 0)
                {
                    // 发生战斗
                    hero.stateMachine.ChangeState(HeroBattleState.Instance);
                    foreach (var monster in monsters)
                    {
                        MessageDispatcher.Instance.DispatchMsg(0, hero.ID(), monster.ID(),
                            MessageType.EnterBattle);
                    }
                
                    hero.SetTargetPosition(currentWaryPoint);
                    return;
                }
            }

            Vector2 targetPosition = path.CurrentWayPoint();;
            Vector2 nextTargetPosition = path.GetNextWayPoint();
            if ((targetPosition - position).normalized - (nextTargetPosition - position).normalized == Vector2.zero)
            {
                hero.SetTargetPosition(nextTargetPosition);
            }
            else
            {
                hero.SetTargetPosition(targetPosition);
            }
        }

        public void Exit(Hero hero)
        {
        }

        public bool OnMessage(Hero hero, Telegram msg)
        {
            return false;
        }
    }
}